package com.example.demoJDBC;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookDao bookDao;


    @GetMapping("/books")
    public ModelAndView showBooks() {

        // 从数据库中获取图书数据
        List<Book> books = bookDao.findAllBooks();
        // 过滤出Java相关图书
        List<Book> javaBooks = new ArrayList<>();
        for (Book book : books) {
            if (book.getTitle().toLowerCase().contains("java")) {
                javaBooks.add(book);
            }
        }

        // 过滤出Spring相关图书名称
        List<String> springBooks = new ArrayList<>();
        for (Book book : books) {
            if (book.getTitle().toLowerCase().contains("spring")) {
                springBooks.add(book.getTitle());
            }
        }

        // 创建ModelAndView对象. 指定视图名称为booklist，即会渲染booklist.html文件
        ModelAndView modelAndView = new ModelAndView("booklist");
        modelAndView.addObject("allBooks", books);
        modelAndView.addObject("javaBooks", javaBooks);
        modelAndView.addObject("springBooks", springBooks);

        return modelAndView;
    }

    @PostMapping("/bookInput")
    public String bookInput(Book book) {
        bookDao.add(book);
        return "redirect:/books";
    }

    @GetMapping("/bookInput")
    public String showBookInputPage() {
        return "redirect:/books"; // 返回 bookInput.html 页面

    }
}
